
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Moving Square on Hover</title>
<style>
  #movingSquare {
    width: 500px;
    height: 500px;
    background-color: #1bf2bc;
    position: relative;
    transition: left 0.5s ease;
  }
</style>
</head>
<body>

<div id="movingSquare"></div>

<script>
  const movingSquare = document.getElementById('movingSquare');

  movingSquare.addEventListener('mouseover', function() {
    let currentLeft = parseInt(window.getComputedStyle(this).getPropertyValue('left') || 0, 10);
    const squareWidth = this.offsetWidth;
    const containerWidth = window.innerWidth;

    // 计算新的left值，使正方形左右移动
    let newLeft = currentLeft + squareWidth;
    if (newLeft > containerWidth - squareWidth) {
      newLeft = -squareWidth;
    }

    // 应用新的left值
    this.style.left = newLeft + 'px';
  });

  movingSquare.addEventListener('mouseout', function() {
    // 当鼠标移出时，将正方形移回原位
    this.style.left = '0px';
  });
</script>

</body>
</html>